package com.mygame.gateway.server.handler.codec;

import com.xinyue.network.message.game.GameMessageHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * 解码客户端消息。协议格式为：消息总长度(int 4) + 长度检验码(int 4) + 消息序列号(int 4) + 消息号(int 4) + 服务ID（2）+ 客户端发送时间(long 8)
 * + 版本号(int 4) + 是否压缩(byte 1) + body（变长）
 * 
 * @author wgs
 *
 */
public class DecodeHandler extends ChannelInboundHandlerAdapter {
    private String aesSecret;//对称加密密钥
    
    public void setAesSecret(String aesSecret) {
        this.aesSecret = aesSecret;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
       if(msg instanceof ByteBuf) {
    	ByteBuf byteBuf = (ByteBuf) msg;
    	 try {
            GameMessageHeader header = new GameMessageHeader();
            header.readRequestHeader(byteBuf);
            GateRequestMessage gameMessagePackage = new GateRequestMessage(header,byteBuf,aesSecret);
            ctx.fireChannelRead(gameMessagePackage);
        }finally {
        	 ReferenceCountUtil.safeRelease(byteBuf);
        }
       } else {
    	   ctx.fireChannelRead(msg);
       }
    }
}
